package com.studyv3.test.minio;

import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Component
public class MinioUtil {
    @Autowired
    private MinioClient client;
    public String bucket="study";
    private String baseurl="http://192.168.1.111:9010/";

    /**
     * 创建桶
     * @param bucket 桶的名称*/
    public boolean createBucket(String bucket){
        try {
            //验证名称是否存在
            if(!client.bucketExists(BucketExistsArgs.builder().bucket(bucket).build())){
                client.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 上传文件*/
    public String putObject(String bucket, String objname, InputStream stream){
        try {
            client.putObject(PutObjectArgs.builder().bucket(bucket).object(objname).stream(stream,stream.available(),-1).build());
            return baseurl+bucket+"/"+objname;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 上传文件*/
    public String putObject(String bucket, String objname, byte[] data){
       return putObject(bucket,objname,new ByteArrayInputStream(data));
    }
    /**
     * 删除文件*/
    public boolean delObject(String bucket,String objname){
        try {
            client.removeObject(RemoveObjectArgs.builder().bucket(bucket).object(objname).build());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 获取对象列表
     * */
    public List<String> getObjectList(String bucket){
        List<String> list=new ArrayList<>();
        client.listObjects(ListObjectsArgs.builder().bucket(bucket).build()).forEach(i->{
            try {
                list.add(i.get().objectName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return list;
    }
}
